package v1

import (
	"github.com/gin-gonic/gin"
	log "github.com/sirupsen/logrus"
	"myginblog/model"
	"myginblog/utils/errmsg"
	"myginblog/utils/httpresponse"
	"net/http"
	"strconv"
)

// AddArticle 添加文章
func AddArticle(c *gin.Context) {
	var data model.Article
	err := c.ShouldBindJSON(&data)
	if err != nil {
		log.Error(err)
		r = httpresponse.SetResponseBody(http.StatusBadRequest, err.Error(), "")
		c.JSON(http.StatusOK, r)
		return
	}
	code := model.CreatArticle(&data)
	if code != errmsg.SUCCESS {
		r = httpresponse.SetResponseBody(code, "", data)
		c.JSON(http.StatusOK, r)
		return
	}
	r = httpresponse.SetResponseBody(code, "", data)
	c.JSON(http.StatusOK, r)
}

// todo 查询分类下的所有文章
func GetCatgoryArticleInfo(c *gin.Context) {

}

// GetArticleInfo 查询当个文章信息
func GetArticleInfo(c *gin.Context) {

}

// GetArticle 查询文章列表
func GetArticle(c *gin.Context) {
	pageSize, err := strconv.Atoi(c.Query("pagesize"))
	if err != nil {
		log.Infoln(err)
	}
	pageNum, err := strconv.Atoi(c.Query("pagenum"))
	if err != nil {
		log.Infoln(err)
	}
	data, code := model.GetArticle(pageSize, pageNum)
	if code != errmsg.SUCCESS {
		r = httpresponse.SetResponseBody(code, "", "")
		c.JSON(http.StatusOK, r)
		return
	}
	r = httpresponse.SetResponseBody(errmsg.SUCCESS, "", data)
	c.JSON(http.StatusOK, r)
}

// EditArticle 编辑文章
func EditArticle(c *gin.Context) {
	var data model.Article
	id, err := strconv.Atoi(c.Param("id"))
	if err != nil {
		log.Infoln(err)
	}
	err = c.ShouldBindJSON(&data)
	if err != nil {
		log.Error(err)
		r = httpresponse.SetResponseBody(http.StatusBadRequest, err.Error(), "")
		c.JSON(http.StatusOK, r)
		return
	}
	code := model.EditArticle(id, &data)
	if code != errmsg.SUCCESS {
		r = httpresponse.SetResponseBody(code, "", data)
		c.JSON(http.StatusOK, r)
		c.Abort()
		return
	}
	r = httpresponse.SetResponseBody(errmsg.SUCCESS, "", data)
	c.JSON(http.StatusOK, r)
}

// DeleteArticle 删除文章
func DeleteArticle(c *gin.Context) {
	id, err := strconv.Atoi(c.Param("id"))
	if err != nil {
		log.Infoln(err)
	}
	code := model.DeleteArticle(id)
	if code != errmsg.SUCCESS {
		r = httpresponse.SetResponseBody(code, "", nil)
		c.JSON(http.StatusOK, r)
		return
	}
	r = httpresponse.SetResponseBody(code, "", nil)
	c.JSON(http.StatusOK, r)
}
